#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.
import logging.handlers
print logging

class JobFormatter(logging.Formatter):
    _fmt = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s"
    datefmt="%H:%M:%S"
    

class JobLogHandler(logging.handlers.BufferingHandler):   
    def __init__(self, job, capacity=5):
        logging.handlers.BufferingHandler.__init__(self, capacity)
        self.capacity = capacity
        self.job = job
        formatter = logging.Formatter(fmt="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", datefmt="%H:%M:%S")
        self.setFormatter(formatter)

    def flush(self):
        self.acquire()
        try:
            msg = u"\n".join([self.format(record).decode('utf-8') for record in self.buffer])
            self.buffer = []
            if msg:
                self.job.log += msg
                self.job.log += u"\n"
                self.job.save()
        finally:
            self.release()


